//
//  SHScaleAnimator.m
//  Tradeaider
//
//  Created by 王方伟 on 2017/7/12.
//  Copyright © 2017年 Shinyhub. All rights reserved.
//

#import "SHScaleAnimator.h"
#import "SHScaleAnimatorCoordinator.h"

@interface SHScaleAnimator ()
@end
@implementation SHScaleAnimator
+ (instancetype)scaleAnimatorWithStartView:(UIView *)startView endView:(UIView *)endView scaleView:(UIView *)scaleView{
    SHScaleAnimator *animator = [[SHScaleAnimator alloc] init];
    animator.startView = startView;
    animator.endView = endView;
    animator.scaleView = scaleView;
    return animator;
}

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext{
    return 0.25;
}


- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext{
    UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *presentedView = [transitionContext viewForKey:UITransitionContextFromViewKey];
    BOOL presentation = (toVC.presentingViewController == fromVC);
    if (!presentation && presentedView) {
        presentedView.hidden = YES;
    }
    
    UIView *containerView = transitionContext.containerView;
    if (_startView == nil && _scaleView == nil) {
        return;
    }
    
    CGRect startFrame = [_startView convertRect:_startView.bounds toView:containerView];
    CGRect endFrame = startFrame;
    CGFloat endAlpha = 0.0f;
    
    if (_endView) {
        CGRect relativeFrame = [_endView convertRect:_endView.bounds toView:nil];
        CGRect keyWindowBounds = [UIScreen mainScreen].bounds;
        if (CGRectIntersectsRect(keyWindowBounds, relativeFrame)) {
            endAlpha = 1.0f;
            endFrame = [_endView convertRect:_endView.bounds toView:containerView];
        }
    }
    
    _scaleView.frame = startFrame;
    [containerView addSubview:_scaleView];
    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
        _scaleView.alpha = endAlpha;
        _scaleView.frame = endFrame;
    } completion:^(BOOL finished) {
        UIView *presentedView = [transitionContext viewForKey:UITransitionContextToViewKey];
        if (presentation && presentedView) {
            [containerView addSubview:presentedView];
        }
        [_scaleView removeFromSuperview];
        [transitionContext completeTransition:!transitionContext.transitionWasCancelled];
    }];
}


@end
